/**
  ******************************************************************************
  * @file    SysTick/main.c 
  * @author  MCD Application Team
  * @version V3.4.0
  * @date    10/15/2010
  * @brief   Main program body.
  ******************************************************************************
  * @copy
  *
  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
  *
  * <h2><center>&copy; COPYRIGHT 2010 STMicroelectronics</center></h2>
  */ 

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "system_stm32f10x.h"
#include "stm32f10x.h"
#include "SystemConfig.h"
#include "stm32f10x_it.h"
#include "stdlib.h"
#include "string.h"

/** @addtogroup STM32F10x_StdPeriph_Examples
  * @{
  */

/** @addtogroup SysTick
  * @{
  */ 

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static volatile unsigned long TimingDelay;
//USART_InitTypeDef USART_InitStructure;

/* Private function prototypes -----------------------------------------------*/
void Delay(volatile unsigned long nTime);
void UART_IRQ_Tx(void);
void UART_IRQ_Rx(void);

/* Private functions ---------------------------------------------------------*/

//fenris 20110128
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */

//fenris 20110201 Buffer Queue
/*
typedef struct
{
  char               buffer[256];
  unsigned short     Head;
  unsigned short     Tail;
} Buffer_Queue;
*/
Buffer_Queue ConRxBuf;
Buffer_Queue ConTxBuf;


void Buffer_Queue_Init(Buffer_Queue queue)
{
/*    queue.Head = 0;
    queue.Tail = 0;
    for(int cnt = 0; cnt < 256; cnt++)
        queue.buffer[cnt] = 0;
  */
    memset(&queue, 0, sizeof(queue));
}

void Buffer_Queue_Write(Buffer_Queue *queue, char *source, unsigned short len)
{
  
    for(int cnt = 0; cnt < len; cnt++)
    {
        queue->buffer[queue->Tail++] = source[cnt];
        if(queue->Head == queue->Tail)
        {
            break;
        }
        if(queue->Tail == CON_RX_BUF_SIZE)
            queue->Tail = 0;
        queue->Length++;
    }
}

void Buffer_Queue_Read(Buffer_Queue *queue, char *target, unsigned short len)
{
    int cnt = 0;
    //while(queue.Head != queue.Tail)
    while( (len > 0) && (queue->Head != queue->Tail) )
    {
        target[cnt++] = queue->buffer[queue->Head++];
        if(queue->Head == CON_RX_BUF_SIZE)
            queue->Head = 0;
        queue->Length--;
        len--;
    }
}

/*char ConRxBuf[256]= {0};
int ConRxHead = 0, ConRxTail = 0;
char ConTxBuf[256]= {0};
int ConTxCnt = 0, ConTxTail = 0;
*/
unsigned char console_flag = 0;
int main(void)
{
    System_Init();
    
    Buffer_Queue_Init(ConRxBuf);
    Buffer_Queue_Init(ConTxBuf);
    char Rxtmp[256] = {0}, Txtmp[256] = {0};
    
    
    NVIC_InitTypeDef		NVIC_InitStructure;
	GPIO_InitTypeDef		GPIO_InitStructure;
	USART_InitTypeDef		USART_InitStructure;
	USART_ClockInitTypeDef	USART_ClockInitStructure;
	EXTI_InitTypeDef		EXTI_InitStructure;
	

	/* clock setting */
	//RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);

	/* GPIO Setting */
	/* PA9: UART TX */
	GPIO_InitStructure.GPIO_Pin		= GPIO_Pin_10;
	GPIO_InitStructure.GPIO_Mode	= GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Speed	= GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	/* PA10: UART RX */
	GPIO_InitStructure.GPIO_Pin		= GPIO_Pin_11;
	GPIO_InitStructure.GPIO_Mode	= GPIO_Mode_IN_FLOATING;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	/* NVIC Setting */
	NVIC_InitStructure.NVIC_IRQChannel				= USART3_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority	= 1;    //IRQ_USART1;
	NVIC_InitStructure.NVIC_IRQChannelCmd			= ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	
	NVIC_InitStructure.NVIC_IRQChannel				= EXTI15_10_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority	= 3;    //IRQ_EXTI_15_10;
	NVIC_InitStructure.NVIC_IRQChannelCmd			= ENABLE;
	NVIC_Init(&NVIC_InitStructure);
    

	/* EXTI Setting */      
	EXTI_ClearITPendingBit(EXTI_Line12);
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource12);
	EXTI_InitStructure.EXTI_Mode	= EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Line	= EXTI_Line12;
	EXTI_InitStructure.EXTI_Trigger	= EXTI_Trigger_Rising_Falling;
	EXTI_InitStructure.EXTI_LineCmd	= ENABLE;
	EXTI_Init(&EXTI_InitStructure);
	EXTI_ClearITPendingBit(EXTI_Line12);
    

	/* USART3 Setting */
	USART_InitStructure.USART_BaudRate		= 57600;    //UART_BAUDRATE;
	USART_InitStructure.USART_WordLength	= USART_WordLength_8b;
	USART_InitStructure.USART_StopBits		= USART_StopBits_1;
	USART_InitStructure.USART_Parity		= USART_Parity_No;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode			= USART_Mode_Rx | USART_Mode_Tx;
	
	USART_ClockInitStructure.USART_Clock		= USART_Clock_Disable;
	USART_ClockInitStructure.USART_CPOL			= USART_CPOL_Low;
	USART_ClockInitStructure.USART_CPHA			= USART_CPHA_2Edge;
	USART_ClockInitStructure.USART_LastBit		= USART_LastBit_Disable;
	
	
	USART_Init(USART3, &USART_InitStructure);
	USART_ClockInit(USART3, &USART_ClockInitStructure);
	//USART_ITConfig(USART3, USART_IT_TXE, ENABLE);
    USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
	USART_Cmd(USART3, ENABLE);
	
	//UART_Detect_IRQ_Callback();

    
        
    /* USARTx configuration ------------------------------------------------------*/
  /* USARTx configured as follow:
        - BaudRate = 9600 baud  
        - Word Length = 8 Bits
        - Two Stop Bit
        - Odd parity
        - Hardware flow control disabled (RTS and CTS signals)
        - Receive and transmit enabled
  */
  /*USART_InitStructure.USART_BaudRate = 57600;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    */

  //STM_EVAL_COMInit(COM1, &USART_InitStructure);

  /* Enable the EVAL_COM1 Transmoit interrupt: this interrupt is generated when the 
     EVAL_COM1 transmit data register is empty */  
  //USART_ITConfig(USART3, USART_IT_TXE, ENABLE);

  /* Enable the EVAL_COM1 Receive interrupt: this interrupt is generated when the 
     EVAL_COM1 receive data register is not empty */
  //USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);

    //USART_SendData(USART3, 0x41);
    //while(USART_GetITStatus(USART3, USART_IT_TXE) != RESET)
    
   // char tmp;
    
    
  while (1)
  {
 /*       USART_SendData(USART3, 0x41);
        while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET){}
        USART_SendData(USART3, 0x42);
        while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET){}
        USART_SendData(USART3, 0x43);
        while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET){}
        USART_SendData(USART3, 0x44);
        while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET){}
        USART_SendData(USART3, 0x45);
        while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET){}
    */
        
 /*       while(USART_GetFlagStatus(USART3, USART_FLAG_RXNE) == RESET){}
        tmp = USART_ReceiveData(USART3);
        USART_SendData(USART3, tmp);
        while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET){}
    */
    
      /*  if((gRTCCnt%10) == 0)
        {
            ConRxBuf[0] = 0;
            ConRxCnt = 0;
        }
    */
    
    
        if(console_flag == 1)
        {
            Buffer_Queue_Read(&ConRxBuf, Rxtmp, ConRxBuf.Length);
            console_flag = 2;
        }
    
    
        if( (console_flag == 2) && (strncmp(Rxtmp, "ati\r\n", 5) == 0) )
        {
            //strcpy(ConTxBuf, "Ver 1.00 Beta 00_BX1");
            Buffer_Queue_Write(&ConTxBuf, "Ver 1.00 Beta 00_BX1\r\n", 22);
            //ConTxCnt = strlen(ConTxBuf);
            //ConRxBuf[0] = 0;
            //ConRxCnt = 0;
            if(ConTxBuf.Head != ConTxBuf.Tail)
                USART_ITConfig(USART3, USART_IT_TXE, ENABLE);
            console_flag = 0;
        }
  }
}
/*
char ConRxBuf[64]= {0};
int ConRxCnt = 0;
char ConTxBuf[64]= {0};
int ConTxCnt = 0;
*/
void UART_IRQ_Tx(void)
{
	char buf[2];

	//if (gTxQBuf.use != 0)
    if(ConTxBuf.Head != ConTxBuf.Tail)
	{
		//QBuf_Read(&gTxQBuf, &buf, 1);
		//USART_SendData(USART3, ConTxBuf[--ConTxCnt]);
        Buffer_Queue_Read(&ConTxBuf, buf, 1);
        USART_SendData(USART3, buf[0]);
	}
	else
	{
		USART_ITConfig(USART3, USART_IT_TXE, DISABLE);
		//*pFlag_console_tx_busy = 0;
        
	}
}

void UART_IRQ_Rx(void)
{
	char buf;//[2];
    //unsigned short tmp;
	buf = USART_ReceiveData(USART3);
   // Buffer_Queue_Write(ConRxBuf, buf, 1);
    ConRxBuf.buffer[ConRxBuf.Tail++] = buf;
    ConRxBuf.Length++;
    if(ConRxBuf.Tail == CON_RX_BUF_SIZE)
        ConRxBuf.Tail = 0;
	//QBuf_Write(&gRxQBuf, &buf, 1);
    /*if(ConRxBuf.Tail > ConRxBuf.Head + 2)
    {
        if( (ConRxBuf.buffer[ConRxBuf.Tail-2] == '\r') && (ConRxBuf.buffer[ConRxBuf.Tail-1] == '\n') )
            console_flag = 1;
    }
    */
    if( (ConRxBuf.State == 0) && (buf == '\r') )
        ConRxBuf.State = 1;
    if( (ConRxBuf.State == 1) && (buf == '\n') )
    {
        console_flag = 1;
        ConRxBuf.State = 0;
    }
}



/**
  * @brief  Inserts a delay time.
  * @param  nTime: specifies the delay time length, in milliseconds.
  * @retval None
  */
void Delay(volatile unsigned long nTime)
{ 
  TimingDelay = nTime;

  while(TimingDelay != 0);
}

/**
  * @brief  Decrements the TimingDelay variable.
  * @param  None
  * @retval None
  */
void TimingDelay_Decrement(void)
{
  if (TimingDelay != 0x00)
  { 
    TimingDelay--;
  }
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @}
  */

/**
  * @}
  */



/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
